package pers.qianyu.month_202101.date_20210111;

import java.util.*;

/**
 * 279. 完全平方数
 * https://leetcode-cn.com/problems/perfect-squares/
 *
 * @author mizzle rain
 * @date 2021-01-11 14:16
 */
public class NumSquares2 {
    // 看成完全背包问题
    public int numSquares(int n) {
        ArrayList<Integer> nums = new ArrayList<>();
        int a = 1;
        while (a * a <= n) {
            nums.add(a * a);
            a++;
        }
        int[] dp = new int[n + 1];
        Arrays.fill(dp, n + 1);
        dp[0] = 0;
        for (int num : nums) {
            for (int i = num; i <= n; i++) {
                dp[i] = Math.min(dp[i - num] + 1, dp[i]);
            }
        }
        return dp[n];
    }

    // 广搜，超时 502 / 588 个通过测试用例
    public int numSquares2(int n) {
        ArrayList<Integer> nums = new ArrayList<>();
        int a = 1;
        while (a * a <= n) {
            nums.add(a * a);
            a++;
        }

        int depth = 1;
        Queue<Integer> q = new LinkedList<>();
        q.add(0);
        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                int cur = q.poll();
                for (int t : nums) {
                    t = t + cur;
                    if (t == n) {
                        return depth;
                    } else if (t > n) {
                        break;
                    }
                    q.offer(t);
                }
            }
            depth++;
        }
        return 0;
    }
}
